import 'package:flutter/material.dart';
import 'dart:ui';

/*
通过addListener()和setState() 来更新UI这一步其实是通用的，
如果每个动画中都加这么一句是比较繁琐的。
AnimatedWidget类封装了调用setState()的细节，并允许我们将Widget分离出来
*/
class AnimatedImage extends AnimatedWidget {
  AnimatedImage({Key key, Animation<double> animation})
      : super(key: key, listenable: animation);

  @override
  Widget build(BuildContext context) {
    final Animation<double> animation = listenable;
    return AnimatedBuilder(
      animation: animation,
      child: Image.asset(
        'assets/images/food05.jpeg',
        width: animation.value,
        fit: BoxFit.fitWidth,
      ),
      builder: (BuildContext ctx, Widget child) {
        return Center(
          child: Container(
            // height: animation.value,
            width: animation.value,
            child: child,
          ),
        );
      },
    );
  }
}

class TestRoute extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return TestRouteState();
  }
}

class TestRouteState extends State<TestRoute>
    with SingleTickerProviderStateMixin {
  Animation<double> animation;
  AnimationController controller;

  dispose() {
    //路由销毁时需要释放动画资源
    controller.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    controller = new AnimationController(
        duration: const Duration(seconds: 3), vsync: this);
    //图片宽高从0变到300
    animation = new Tween(begin: 0.0, end: window.physicalSize.width)
        .animate(controller);
    //启动动画
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('优化代码'),
      ),
      body: Center(
        child: AnimatedImage(
          animation: animation,
        ),
      ),
    );
  }
}
